package net.neiquan.applibrary.wight;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.view.ViewPager.PageTransformer;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;


import net.neiquan.applibrary.R;
import net.neiquan.applibrary.inter.CustomViewPagerClickListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 类描述: 轮播图片View
 */
@SuppressLint("HandlerLeak")
public class CustomViewPager extends FrameLayout implements OnGestureListener {

    private ImageHandler mhandler = new ImageHandler(
            new WeakReference<CustomViewPager>(this));
    private List<String> imageUris;
    private List<String> flashTitles;
    private List<View> imageViewsList;
    private List<ImageView> dotViewsList;// 点的
    private LinearLayout mLinearLayout;// 点的线性布局
    private LinearLayout llback;// 半透明的背景色
    private ViewPager mViewPager;
    private CustomViewPagerClickListener mFlashViewListener;// 向外提供接口
    //	private int dot2 = R.drawable.dot_white;// 没有选中的点
//	private int dot1 = R.drawable.dot_base;// 当前选中的点
    private int dot2 = R.drawable.lunbo_;// 没有选中的点
    private int dot1 = R.drawable.lunbo;// 当前选中的点
    private int dotMargin = 15;// 点之间的间隙 单位 是px
    private MyPagerAdapter adapter;
    private LinearLayout.LayoutParams lp; //可以调小图标的大小
    private GestureDetector mGestureDetector;// 增加长按停止轮播的手势检测

    // private RelativeLayout relFlashApha;

    private LayoutInflater inflater;

    public CustomViewPager(Context context) {
        this(context, null);

    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomViewPager(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initUI(context);
        if (!(imageUris.size() <= 0)) {
            setImageUris(imageUris, flashTitles);
        }
    }

    private void initUI(Context context) {
        imageViewsList = new ArrayList<View>();
        dotViewsList = new ArrayList<ImageView>();
        imageUris = new ArrayList<String>();
        flashTitles = new ArrayList<String>();
        mGestureDetector = new GestureDetector(context, this);
        LayoutInflater.from(context).inflate(R.layout.layout_flash_news_view,
                this, true);
        mLinearLayout = (LinearLayout) findViewById(R.id.linearlayout_flash2);
        llback = (LinearLayout) findViewById(R.id.ll_flash_backgroud);
//        llback.getBackground().setAlpha(20);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        inflater = (LayoutInflater) LayoutInflater.from(context);

    }

    public void setImageUris(List<String> imageuris, List<String> flashtitles) {
        this.imageUris.clear();
        this.imageViewsList.clear();
        flashTitles.clear();
        dotViewsList.clear();
        mLinearLayout.removeAllViews();
        if (imageuris == null || imageuris.size() <= 0) {// 如果得到的图片张数为0，则增加一张默认的图片
            imageUris.add("drawable://" + R.drawable.pictures_no2
            );
        } else {
            for (int i = 0; i < imageuris.size(); i++) {
                imageUris.add(imageuris.get(i));
            }
        }
        //布局里面的圆点图标大小,在这里可以调
        if (lp == null) {
            lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.gravity= Gravity.CENTER_VERTICAL;
            lp.setMargins(dotMargin, 0, 0, 0);  //左上右下
        }
        for (int i = 0; i < imageUris.size(); i++) {
            View viewFlash = inflater.inflate(
                    R.layout.layout_flash_news_view_item, null);
            SimpleDraweeView imageView = (SimpleDraweeView) viewFlash
                    .findViewById(R.id.img_flash_news);
            TextView tvTitle = (TextView) viewFlash
                    .findViewById(R.id.tv_news_flash_title);
//            ImageLoader.getInstance().displayImage(imageUris.get(i), imageView);
            int width = 480, height = 300;
            if (!TextUtils.isEmpty(imageUris.get(i))) {
                try {
                    Uri uri = Uri.parse(imageUris.get(i));
                    ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                            .setResizeOptions(new ResizeOptions(width, height))
                            .build();
                    PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                            .setOldController(imageView.getController())
                            .setImageRequest(request)
                            .build();
                    imageView.setController(controller);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//            imageView.setImageURI(imageUris.get(i));
            imageViewsList.add(viewFlash);
            if (flashtitles != null) {
                tvTitle.setText(flashtitles.get(i));
            } else {
                tvTitle.setVisibility(GONE);
                ImageView viewDot = new ImageView(getContext());
                if (i == 0) {
                    viewDot.setBackgroundResource(dot1);
                } else {
                    viewDot.setBackgroundResource(dot2);
                }
                viewDot.setLayoutParams(lp);
                dotViewsList.add(viewDot);
                mLinearLayout.addView(viewDot);
            }
        }
        mViewPager.setFocusable(true);
        if (adapter == null) {
            adapter = new MyPagerAdapter();
            mViewPager.setAdapter(adapter);
            mViewPager.setOnPageChangeListener(new MyPageChangeListener());
            if (imageUris.size() <= 1) {

            } else {
                mViewPager.setCurrentItem(100 * imageViewsList.size());

                mhandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE,
                        ImageHandler.MSG_DELAY);
            }
        }
//        adapter.notifyDataSetChanged();
    }

    /**
     * 切换轮播小点的显示
     *
     * @param selectItems
     */
    private void setImageBackground(int selectItems) {
        for (int i = 0; i < dotViewsList.size(); i++) {
            if (i == selectItems % dotViewsList.size()) {
                dotViewsList.get(i).setBackgroundResource(dot1);
            } else {
                dotViewsList.get(i).setBackgroundResource(dot2);
            }
        }
    }

    /**
     * 数据适配器
     */
    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public void destroyItem(View container, int position, Object object) {

        }

        @Override
        public Object instantiateItem(View container, int position) {
            position = position % imageViewsList.size();

            if (position < 0) {
                position = position + imageViewsList.size();

            }
            final int pos = position;
            View view = imageViewsList.get(position);
            view.setTag(position);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mFlashViewListener != null) {
                        mFlashViewListener.onItemClick(pos);
                    }
                }
            });
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewPager pager = (ViewPager) vp;
                pager.removeView(view);
            }
            ((ViewPager) container).addView(view);
            return view;
        }

        @Override
        public int getCount() {
            if (imageUris.size() <= 1) {
                return 1;
            } else {
                return Integer.MAX_VALUE;
            }

        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
    }

    private class MyPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

            switch (arg0) {
                case ViewPager.SCROLL_STATE_DRAGGING:
                    mhandler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                    break;
                case ViewPager.SCROLL_STATE_IDLE:
                    mhandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE,
                            ImageHandler.MSG_DELAY);
                    break;
                default:
                    break;
            }

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
            mhandler.sendMessage(Message.obtain(mhandler,
                    ImageHandler.MSG_PAGE_CHANGED, pos, 0));
            setImageBackground(pos);

        }

    }

    @SuppressWarnings("unused")
    // private void destoryBitmaps() {
    // for (int i = 0; i < imageViewsList.size(); i++) {
    // ImageView imageView = imageViewsList.get(i);
    // Drawable drawable = imageView.getDrawable();
    // if (drawable != null) {
    // drawable.setCallback(null);
    // }
    // }
    // }
    public void stopScroll(){
        if (mhandler!=null){
            mhandler.removeMessages(ImageHandler.MSG_UPDATE_IMAGE);
            mhandler.removeMessages(ImageHandler.MSG_KEEP_SILENT);
            mhandler.removeMessages(ImageHandler.MSG_BREAK_SILENT);
            mhandler.removeMessages(ImageHandler.MSG_PAGE_CHANGED);
        }
    }
    public void setPageTransformer(PageTransformer rotateTransformer) {
        // TODO Auto-generated method stub
        mViewPager.setPageTransformer(false, rotateTransformer);
    }

    private static class ImageHandler extends Handler {

        public static final int MSG_UPDATE_IMAGE = 1;

        public static final int MSG_KEEP_SILENT = 2;

        public static final int MSG_BREAK_SILENT = 3;

        public static final int MSG_PAGE_CHANGED = 4;

        protected static final long MSG_DELAY = 4000;

        private WeakReference<CustomViewPager> weakReference;
        private int currentItem = 0;

        protected ImageHandler(WeakReference<CustomViewPager> wk) {
            weakReference = wk;

        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            CustomViewPager activity = weakReference.get();
            if (activity == null) {
                return;
            }
            if (activity.mhandler.hasMessages(MSG_UPDATE_IMAGE)) {
                if (currentItem > 0)// 这里必须加入currentItem>0的判断，否则不能完美的自动轮播
                {
                    activity.mhandler.removeMessages(MSG_UPDATE_IMAGE);
                }
            }
            switch (msg.what) {
                case MSG_UPDATE_IMAGE:

                    currentItem++;
                    activity.mViewPager.setCurrentItem(currentItem);
                    activity.mhandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE,
                            MSG_DELAY);
                    break;
                case MSG_KEEP_SILENT:
                    break;
                case MSG_BREAK_SILENT:
                    activity.mhandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE,
                            MSG_DELAY);
                    break;
                case MSG_PAGE_CHANGED:
                    currentItem = msg.arg1;
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * 设置点击图片点击监听
     *
     * @param mListener
     */
    public void setOnCustomViewPagerClickListener(CustomViewPagerClickListener mListener) {
        mFlashViewListener = mListener;
    }

    /**
     * 设置点的位置 可以设置左 右 居中
     *
     * @param gravity
     */
    public void setDogGravity(int gravity) {
        mLinearLayout.setGravity(gravity);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_CANCEL
                || ev.getAction() == MotionEvent.ACTION_UP) {
            mhandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, 500);
        }
        mGestureDetector.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        mhandler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        // TODO Auto-generated method stub
        return false;
    }
}
